#pragma once
#include <iostream>
#include "oj_model.hpp"
#include "oj_view.hpp"
#include <jsoncpp/json/json.h>
#include <mutex>
#include "../comm/httplib.h"
namespace ns_control
{
    using namespace ns_model;
    using namespace ns_view;
    using namespace httplib;
    using namespace ns_log;
    using namespace ns_util;
    // 提供服务的主机
    struct machine
    {
        std::string ip;  // 编译服务的ip
        int port;        // 编译服务的port
        uint64_t load;   // 编译服务的负载
        std::mutex *mtx; // mutex禁止拷贝的，使用指针
        // 提升主机负载
        void incload()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // 减少主机负载
        void decload()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
        void ResetLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }
    };
    const std::string service_machine = "./conf/service_machine.conf";
    // 负载均衡模块
    class loadblance
    {
    private:
        // 可以给我们提供编译服务的所有的主机
        // 每一台主机都有自己的下标，充当当前主机的id
        std::vector<machine> machines;
        // 所有在线的主机id
        std::vector<int> online;
        // 所有离线的主机id
        std::vector<int> offline;
        // 保证LoadBlance它的数据安全
        std::mutex mtx;

    public:
        loadblance()
        {
            assert(loadconf(service_machine));
        }
        ~loadblance() {}

    public:
        bool loadconf(const std::string &s_m)
        {
            std::ifstream in(s_m);
            if (!in.is_open())
            {
                LOG(ERROR) << "负载文件加载失败" << std::endl;
            }
            std::string line;
            while (getline(in, line))
            {
                std::vector<std::string> tonk;
                FileUtil::splits(line, &tonk, ":");
                if (tonk.size() != 2)
                {
                    LOG(WARNING) << "负载均衡所切的格式错误" << std::endl;
                }
                machine m;
                m.ip = tonk[0];
                m.port = atoi(tonk[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();
                online.push_back(machines.size());
                machines.push_back(m);
            }
            in.close();
            return true;
        }
        bool smartmachine(int *id, machine **m)
        {
            mtx.lock();
            // 负载均衡的算法
            // 1. 随机数+hash
            // 2. 轮询+hash
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(FATAL) << " 所有的后端编译主机已经离线, 请运维的同事尽快查看"
                           << "\n";
                return false;
            }
            // 通过遍历的方式，找到所有负载最小的机器
            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].load;
            for (int i = 1; i < online_num; i++)
            {
                uint64_t curr_load = machines[online[i]].load;
                if (min_load > curr_load)
                {
                    min_load = curr_load;
                    *id = online[i];
                    *m = &machines[online[i]];
                }
            }
            mtx.unlock();
            return true;
        }
        void offlinemachine(int which)
        {
            mtx.lock();
            for (auto iter = online.begin(); iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[which].ResetLoad();
                    // 要离线的主机已经找到啦
                    online.erase(iter);
                    offline.push_back(which);
                    break; // 因为break的存在，所有我们暂时不考虑迭代器失效的问题
                }
            }
            mtx.unlock();
        }
        void onlinemachine()
        {
            mtx.lock();
            online.insert(online.end(), offline.begin(), offline.end());
            offline.erase(offline.begin(), offline.end());
            mtx.unlock();

            LOG(INFO) << "所有的主机有上线啦!" << "\n";
        }
    };
    class control
    {
    public:
        control() {}
        ~control() {}
        bool allquestions(std::string *html)
        {
            std::vector<question> all;
            if (_model.getallquestions(&all))
            {
                //LOG(DEBUG)<<"问题总数"<<all.size()<<std::endl;
                sort(all.begin(), all.end(), [](const question &q1, const question &q2){
                    return atoi(q1.number.c_str()) < atoi(q2.number.c_str());
                });
                // 构建网页
                _view.allqexpand(all, html);
                //LOG(DEBUG) << "网页构建成功" << std::endl;
            }
            else
            {
                *html = "获取题目失败, 形成题目列表失败";
                return false;
            }
            return true;
        }
        bool onequestion(const std::string &nums, std::string *html)
        {
            question q;
            if (_model.getonequestion(nums, &q))
            {
                // 构建网页
                _view.oneqexpand(q, html);
            }
            else
            {
                *html = "指定题目: " + nums + " 不存在!";
                return false;
            }
            return true;
        }
        void judge(const std::string &number,const std::string &in_json, std::string *out_json)
        {
            // 0. 根据题目编号，直接拿到对应的题目细节
             question q;
            _model.getonequestion(number, &q);

            // 1. in_json进行反序列化，得到题目的id，得到用户提交源代码，input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            // 2. 重新拼接用户代码+测试用例代码，形成新的代码
            Json::Value compile_value;
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);

            // 3. 选择负载最低的主机(差错处理)
            // 规则: 一直选择，直到主机可用，否则，就是全部挂掉
            while(true)
            {
                int id = 0;
                machine *m = nullptr;
                if(!_loadblance.smartmachine(&id, &m))
                {
                    break;
                }

                // 4. 然后发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->incload();
                LOG(INFO) << " 选择主机成功, 主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 当前主机的负载是: " << m->load << "\n";
                if(auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    // 5. 将结果赋值给out_json
                    if(res->status == 200)
                    {
                        *out_json = res->body;
                        m->decload();
                        LOG(INFO) << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                    m->decload();
                }
                else
                {
                    //请求失败
                    LOG(ERROR) << " 当前请求的主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 可能已经离线"<< "\n";
                    _loadblance.offlinemachine(id);
                }
            }
        }
        

    private:
        model _model;
        view _view;
        loadblance _loadblance;
    };
}